package com.leo.base.db.aop;

import com.leo.base.db.DynamicDataSourceContextHolder;
import com.leo.base.db.SqlDmlCacheSmartLifecycle;
import com.leo.base.db.annotation.UnionDataSource;
import com.leo.base.db.router.rule.UnionRule;
import com.leo.base.exception.CustomException;
import com.leo.base.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.SqlCommandType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wangss
 */
@Slf4j
@Aspect
@Component
public class UnionDataSourceAspect {

    private static final int MAXSIZE = 50;

    private static final String ERROR = "UnionDataSource annotation error!!!";

    @Pointcut("@annotation(com.leo.base.db.annotation.UnionDataSource)")
    public void pointcut() {
        // 不做处理
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws CustomException {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String methodName = method.getName();
        log.info("Method [{}] UnionDataSource begin to change datasource", methodName);
        UnionDataSource annotation = method.getAnnotation(UnionDataSource.class);
        if (null == annotation) {
            annotation = method.getDeclaringClass().getAnnotation(UnionDataSource.class);
            if (null == annotation) {
                log.error("Method [{}] can not find UnionDataSource annotation", methodName);
                throw new CustomException(ERROR);
            }
        }

        String tableName = annotation.tableName();
        if (StringUtils.isBlank(tableName)) {
            log.error("Method [{}] get tableName of Annotation UnionDataSource is null", methodName);
            throw new CustomException(ERROR);
        }

        UnionRule rule = (UnionRule) SpringContextUtil.getBean(tableName);
        if (null == rule) {
            log.error("Method [{}] get bean of UnionRule is null", methodName);
            throw new CustomException(ERROR);
        }

        // 获取所有数据源
        String[] dataSourceKey = rule.getDataSourceKey();
        // 如果是查询，则继续处理
        if (!SqlCommandType.SELECT.name().equals(SqlDmlCacheSmartLifecycle.getSqlDmlType(methodName))) {
            log.error("Method [{}] sql dml type is [{}], can not deal", methodName, SqlDmlCacheSmartLifecycle.getSqlDmlType(methodName));
            throw new CustomException(ERROR);
        }

        // 获取方法的返回类型
        Class<?> returnType = method.getReturnType();
        int dataSourceLength = dataSourceKey.length;
        // 如果是集合类型
        if (Collection.class.isAssignableFrom(returnType)) {
            int total = 0;
            List<Object> resultList = new ArrayList<>(MAXSIZE);
            for (int i = 0; i < dataSourceLength; i++) {
                DynamicDataSourceContextHolder.clearDataSourceKey();
                DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey[i]);
                log.info("Method [{}] UnionDataSource switching datasource to [{}]", methodName, dataSourceKey[i]);
                try {
                    List list = (List) joinPoint.proceed();
                    if (null == list || list.isEmpty()) {
                        continue;
                    }
                    total = dealResultList(total, resultList, list);
                    if (total >= MAXSIZE) {
                        break;
                    }
                } catch (Throwable throwable) {
                    log.error("Method [{}] UnionDataSource select collection error, reason [{}]", methodName, throwable.getMessage());
                    throw new CustomException(throwable.getMessage());
                }
            }
            return resultList;
        } else {
            // 如果是其他类型，则查到数据就返回
            for (int i = 0; i < dataSourceLength; i++) {
                DynamicDataSourceContextHolder.clearDataSourceKey();
                DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey[i]);
                log.info("Method [{}] UnionDataSource switching datasource to [{}]", methodName, dataSourceKey[i]);
                try {
                    Object object = joinPoint.proceed();
                    if (null == object) {
                        continue;
                    }
                    return object;
                } catch (Throwable throwable) {
                    log.error("Method [{}] UnionDataSource select object error, reason [{}]", methodName, throwable.getMessage());
                    throw new CustomException(throwable.getMessage());
                }
            }
            return null;
        }
    }

    @After("pointcut()")
    public void after() {
        DynamicDataSourceContextHolder.clearDataSourceKey();
    }

    private int dealResultList(int total, List<Object> resultList, List list) {
        if (total < MAXSIZE) {
            if (total + list.size() <= MAXSIZE) {
                resultList.addAll(list);
                return total + list.size();
            } else {
                int min = MAXSIZE - total;
                resultList.addAll(list.subList(0, min));
                return MAXSIZE;
            }
        }
        return total;
    }
}
